package com.hwua.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hwua.entity.*;
import com.hwua.service.IProductService;
import com.hwua.service.IShopCartService;
import com.hwua.service.Impl.ProductAllServiceImpl;
import com.hwua.service.Impl.ProductServiceImpl;
import com.hwua.service.Impl.ShopCartServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.*;

@WebServlet("/product")
public class ProductServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        String param = request.getParameter("param");
        String id = request.getParameter("id");
        ProductAllServiceImpl productAllService = new ProductAllServiceImpl();
        HttpSession session = request.getSession(false);
        try {
            Product products = productAllService.queryByProdId(Integer.parseInt(id));
            session.setAttribute("NOHA", products);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (param.equals("item")) {
            session.setAttribute("twoid",id);
            try {
                List<Product> products = productAllService.queryById(Integer.parseInt(id));
                request.setAttribute("lists", products);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                IProductService productService=new ProductServiceImpl();
                Product product = productAllService.queryByMinorID(Integer.parseInt(id));
                ProductCategory productCategorys = productService.queryBySelfID((int) product.getMinor_id());
                request.setAttribute("first",productCategorys);
                ProductCategory productCategory = productService.queryBySelfID((int) product.getMajor_id());
                request.setAttribute("third",productCategory);//一级目录
            } catch (Exception e) {
                e.printStackTrace();
            }
            request.getRequestDispatcher("/product-list.jsp").forward(request, response);
        }

        else if (param.equals("items")) {
            try {
                Product product = productAllService.queryByProdId(Integer.parseInt(id));//根据这个id1查询出其内容
                request.getRequestDispatcher("/product-list.jsp").forward(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        else if (param.equals("shop")) {
            String twoid = (String)session.getAttribute("twoid");
            IProductService productService=new ProductServiceImpl();
            try {
                Product product = productAllService.queryByMinorID(Integer.parseInt(twoid));
                ProductCategory productCategorys = productService.queryBySelfID((int) product.getMinor_id());
                request.setAttribute("firt",productCategorys);
                ProductCategory productCategory = productService.queryBySelfID((int) product.getMajor_id());
                request.setAttribute("thir",productCategory);//一级目录
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Product product = productAllService.queryByProdId(Integer.parseInt(id));
                String histroyId = linkId(id, request);//获取拼好的商品id,格式:1-2-3-4
                Cookie cookie = new Cookie("histroyId", histroyId);
                response.addCookie(cookie);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Product product = productAllService.queryByProdId(Integer.parseInt(id));
                session.setAttribute("pro", product);
                System.out.println(product);
            } catch (Exception e) {
                e.printStackTrace();
            }
            request.getRequestDispatcher("/product_view.jsp").forward(request, response);
        }

        else if (param.equals("shopCarItem")) {
            List<ProductExtend> list = new ArrayList<>();
            List<ProductExtend>list1=new ArrayList<>();
            Product product = (Product) session.getAttribute("pro");
            System.out.println(product);
            Integer count = request.getParameter("count") != null && !request.getParameter("count").equals("") ? Integer.parseInt(request.getParameter("count")) : null;
            IShopCartService shopCartService=new ShopCartServiceImpl();
            try {
                User user=(User)session.getAttribute("user");
                if(user!=null){
                    list=shopCartService.queryShopCartByuid(user.getId());
                }else{
                    list=shopCartService.queryShopCartByuid(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //设置总数
            for (ProductExtend product1 : list) {
                try {
                    ShopCart shopCarts=shopCartService.queryShopCartBypid((int) product1.getId()).get(0);
                    product1.setCount((int) shopCarts.getPnum());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(list);
            ShopingCartReal shopingCartReal=new ShopingCartReal();
            request.setAttribute("ShopCartList",list);
//            request.setAttribute("count",count);
                /*Cookie[] cookies = request.getCookies();
                boolean flag = false;//默认没有找到指定名字的cookie
                if (cookies != null && cookies.length > 0) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("ShopCartId")) {
                            flag = true;//找到
                            String value = cookie.getValue();
                            String[] ids = value.split("-");
                            for (String i : ids) {
                                try {
                                    Product product2 = productAllService.queryByProdId(Integer.parseInt(i));
                                    list.add(product);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            request.setAttribute("produlist", list);
                            break;
                        }
                    }*/
                    request.getRequestDispatcher("/shopping.jsp").forward(request,response);
                }

                /*request.getRequestDispatcher("/shopping.jsp").forward(request, response);*/
        else  if(param.equals("first")){
            List<ProductCategory> productCategories=(List<ProductCategory>)session.getAttribute("firstlist");
            response.getWriter().write(JSON.toJSONString(productCategories));
        }
    }
    //拼接方法(拼接的逻辑都写在这里)
    private String linkId(String id, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String histroyId = null;
        boolean flag = false;//默认没有找到指定名字的cookie
        //非第一次访问的时候
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("histroyId")) {
                    flag = true;
                    histroyId = cookie.getValue();//1-2-3
                    break;
                }
            }
        }

        //浏览第一个商品的时候
        if (cookies == null || flag == false) {
            histroyId = id;
        }

        LinkedList<String> list = new LinkedList<String>(Arrays.asList(histroyId.split("-")));
        //假如长度不满4,冲突:先删除冲突的id,再把id添加到头部,不冲突,直接放到头部

        if (list.size() < 4) {
            if (list.contains(id)) {
                list.remove(id);//先删除
            }
        }

        if (list.size() == 4) {
            if (list.contains(id) == false) {
                list.removeLast();// 删除最后一个id
            } else {
                list.remove(id);//先删除
            }
        }
        list.addFirst(id);//添加到头部
        //动态拼接id
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i > 0) {
                sb.append("-");
            }
            sb.append(list.get(i));//拼接字符串
        }
        return sb.toString();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
